package com.kevinwu.server.servlet;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ServletMapper {

    private static Map<String, Servlet> servletMap = new HashMap<String, Servlet>();

    /**
     * 获取appBase目录下的context
     *
     * @param appBase
     * @return
     */
    private static String getContext(String appBase) {

        String context = "";
        File[] fileList = new File(appBase).listFiles();
        for (File file : fileList) {
            if (file.isDirectory()) {
                context = context + file.getName() + ",";
            }
        }
        return context = context.substring(0, context.length() - 1);
    }

    /**
     * 返回指定路径下的web.xml文件 全路径
     *
     * @param file
     * @return
     */
    private static String showWebxmlPath(File file) {
        File[] fileList = file.listFiles();
        for (File fileName : fileList) {
            if (fileName.isDirectory()) {
                showWebxmlPath(fileName);
            }
            if ("web.xml".equals(fileName.getName())) {
                return fileName.getAbsolutePath();
            }
        }
        return "";
    }

    /**
     * 解析web.xml文件 把路径和servlet匹配上
     *
     * @param jarPath
     * @param contextName 项目名
     * @param webxmlPath  用来获取servlet名，servletl路径
     */
    private static void loadWebxml(String contextName, String jarPath, String webxmlPath) {

        try {
            InputStream resourceAsStream = new FileInputStream(webxmlPath);
            Document document = new SAXReader().read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> selectNodes = rootElement.selectNodes("//servlet");

            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();
                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                //========================================================================
                //jarPath = "D:\\webapps\\demo\\demo1-0.1-SNAPSHOT.jar";
                jarPath = jarPath.replaceAll("//", "////");
                URLClassLoader loader = new URLClassLoader(new URL[]{new URL("file:///" + jarPath)});
                Class<?> aClass = null;
                //由于是使用jar的方式引入，不能读取到类名，写死
                if (jarPath.contains("demo1")) {
                    aClass = loader.loadClass("com.lagou.demo.ServletDemo1");
                } else if (jarPath.contains("demo2")){
                    aClass = loader.loadClass("com.lagou.demo.ServletDemo2");
                }
                Servlet servlet = (Servlet) aClass.newInstance();
                //========================================================================
                servletMap.put("/" + contextName + urlPattern, servlet);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据传入的appBase查找目录下的web.xml文件，并组装成servletMapper
     *
     * @param appBasePath
     * @return
     */
    public static Map<String, Servlet> getServletMapper(String appBasePath) {
        String ContextNames = getContext(appBasePath);
        String[] contextNamesArr = ContextNames.split(",");
        //contextName = demo1
        for (String contextName : contextNamesArr) {
            //D:\Users\W612677.ONEPLUS\Desktop\two-one\code\MyMiniCat\src\main\resources\webapps/demo1
            String contextPath = appBasePath + "/" + contextName;
            // D:\Users\W612677.ONEPLUS\Desktop\two-one\code\MyMiniCat\src\main\resources\webapps\demo1\web.xml
            String webxmlPath = showWebxmlPath(new File(contextPath));
            // D:\webapps\demo1\demo1-0.1-SNAPSHOT.jar
            String jarPath = getJarPath(contextPath);
            loadWebxml(contextName, jarPath, webxmlPath);
        }
        return servletMap;
    }

    private static String getJarPath(String contextPath) {
        String jarPath = null;
        File file = new File(contextPath);
        File[] files = file.listFiles();
        for (File jarFile : files) {
            if (jarFile.getAbsolutePath().contains(".jar")) {
                jarPath = jarFile.getAbsolutePath();
            }
        }
        return jarPath;
    }
}
